using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Net;
using System.IO;

public partial class app_frame_feedback : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        setPageTitle();
        if (!IsPostBack)
        {
            lblStatus.Text = "";
            lblEmailValidate.Text = "";
            if (Request.QueryString["noImage"] != null)
            {
                if (Request.QueryString["noImage"] == "1")
                    Image1.Visible = false;
            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        byte[] content = null;
        if (txtEmail.Text.Length > 0)
        {
            if (!validateRegEx(txtEmail.Text, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
            {
                lblEmailValidate.Text = "(Not a valid E-Mail Address)";
                return;
            }
        }
        lblEmailValidate.Text = "";
        if (FileUpload1.HasFile)
        {
            if (FileUpload1.PostedFile.ContentLength > 2097152)//2147483647
            {
                lblStatus.Text = "Attached screenshot size is more than 2MB.";
                return;
            }
            string ext = "";
            FileInfo fi = new FileInfo(FileUpload1.FileName);
            ext = fi.Extension.ToLower();
            fi = null;
            if (!(ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".png" || ext == ".gif"))
            {
                lblStatus.Text = "Attached screenshot is not a valid image file.";
                return;
            }
            else
            {
                BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);
                content = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
            }
        }
        bool storeDB = false; bool send = false;
        storeDB = storeInDB(txtName.Text, txtEmail.Text.Trim().Length > 0 ? txtEmail.Text : "notspecified@cellarstone.com", txtSubject.Text.Trim().Length > 0 ? txtSubject.Text : "No Subject", txtComments.Text,content,FileUpload1.FileName);
        send = sendMail(txtName.Text, txtEmail.Text.Trim().Length > 0 ? txtEmail.Text : "notspecified@cellarstone.com", txtSubject.Text.Trim().Length > 0 ? txtSubject.Text : "No Subject", txtComments.Text + "<br><br>Generated and send from Feedback form.", content, FileUpload1.FileName);
        //Response.Write("&nbsp;&nbsp;&nbsp;<img src='../Images/cellarstone.gif'><br><font face='Arial' size='10pt'>You suggestions submitted successfully.</font>");
        if (storeDB || send)
        {
            txtSubject.Text = "";
            txtComments.Text = "";
            if (Image1.Visible==true)
                lblStatus.Text = "Your suggestions submitted successfully. <a href='javascript:window.close();'>Click here</a> to close this window";
            else
                lblStatus.Text = "Your suggestions submitted successfully.";
        }
        else
        {
            string emailid = GetDefaultMailID();
            lblStatus.Text = "We are unable to process your request now. Please send a mail to <a href='mailto:"+emailid+"'>"+emailid+"</a>";
        }
    }
    private bool validateRegEx(string input, string exp)
    {        
        try
        {
            bool ret = false;
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(exp);
            ret = re.IsMatch(input);
            re = null;
            return ret;
        }
        catch (Exception e)
        {
            return true;
        }
    }
    private string makeProper(string inp)
    {
        if (inp.Length < 1) return inp;
        return inp.Replace("'", "''");
    }
    private bool storeInDB(string name,string email,string subject,string comments,byte[] screenshot,string attachFileName)
    {
        SqlConnection sc = null;
        try
        {
            string command = "";
            if (screenshot == null)
                command = "insert into feedback(name,email,subject,comments) values('" + makeProper(name) + "','" + makeProper(email) + "','" + makeProper(subject) + "','" + makeProper(comments) + "')";
            else
                command = "insert into feedback(name,email,subject,comments,attachment,attachedFileName) values('" + makeProper(name) + "','" + makeProper(email) + "','" + makeProper(subject) + "','" + makeProper(comments) + "'," + "@pic" + ",'" + makeProper(attachFileName) + "')";
            string dbCon = "";
            if (Session["servercon"] == null)
                dbCon = @"Data Source=csnindsrv010;Initial Catalog=ngmodel;User Id=sa;Password=sa";
            else
                dbCon = Session["servercon"].ToString();
            sc = new SqlConnection(dbCon);
            sc.Open();
            SqlCommand scmd = new SqlCommand(command, sc);
            if (screenshot != null)
                scmd.Parameters.Add("@pic", screenshot);
            int rec = scmd.ExecuteNonQuery();
            scmd = null;
            sc.Close();
            sc = null;
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
        finally
        {
            if (sc != null)
            {
                if (sc.State != ConnectionState.Closed)
                    sc.Close();
                sc = null;
            }
        }
    }
    private bool sendMail(string name, string email, string subject, string comments, byte[] screenshot, string attachFileName)
    {
//        return sendEmail("AppFrame_Support@cellarstone.com", email, true, subject, comments, null, "mail.cellarstone.com", 25, "sync@cellarstone.com", "sync123")=="success";
        //return sendEmail("MaxBlox_Support@cellarstone.com", email, true, subject, comments, screenshot, attachFileName, "mail.cellarstone.com", 25, "sync@cellarstone.com", "sync123") == "success";
        CommonFunctions cf = new CommonFunctions();
        bool ret = false;
        try
        {
            string Emailid = GetDefaultMailID();
            ret = cf.sendEmail(Emailid, email, true, subject, comments, screenshot, attachFileName) == "success";
        }
        catch (Exception e)
        {

        }
        finally
        {
            cf = null;
        }
        return ret;
    }
    //public string sendEmail(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile,string attachmentFileName, string server, int serverPort, string serverUserName, string serverPassword)
    //{
    //    try
    //    {
    //        System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
    //        //eMail = new MailMessage();
    //        if (attachFile != null)
    //        {
    //                    //System.Net.Mail.Attachment att;
    //                    //att = getAttachment(attachFiles[i]);
    //                    //if (att != null)
    //                    //    eMail.Attachments.Add(att);
    //            MemoryStream ms = new MemoryStream(attachFile);
    //            eMail.Attachments.Add(new System.Net.Mail.Attachment(ms,attachmentFileName,"image/png"));
    //        }
    //        eMail.IsBodyHtml = isHTML;
    //        //eMail.BodyFormat = System.Net.Mail.MailFormat.Html;
    //        eMail.Body = content;
    //        eMail.From = new System.Net.Mail.MailAddress(fromAddress);
    //        eMail.Subject = subject;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtsperver"] = server;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
    //        ////////                if (SMTPUser != null && SMTPPassword != null)
    //        ////////                {
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "mail@visioninfomedia.com";
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "indi";
    //        //                }
    //        eMail.To.Add(toAddress);

    //        //System.Net.Mail.SmtpMail.SmtpServer = server;// Smtpmail;// = new System.Net.Mail.SmtpMail();
    //        //System.Net.Mail.SmtpMail.Send(eMail);
    //        System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(server);
    //        sc.Timeout = 400000;
    //        if (serverPort != 0) sc.Port = serverPort;
    //        if (serverUserName.Trim() != "")
    //            sc.Credentials = new NetworkCredential(serverUserName, serverPassword);
    //        else
    //            sc.Credentials = CredentialCache.DefaultNetworkCredentials;
    //        //sc.Credentials  = CredentialCache.

    //        //                Smtpmail.SmtpServer = "localhost";
    //        //                Smtpmail.Send(eMail);
    //        sc.Send(eMail);
    //        eMail = null;
    //        sc = null;
    //        return "success";
    //    }
    //    catch (Exception e)
    //    {
    //        //return false;
    //        return e.Message;
    //    }
    //}
    //private System.Net.Mail.Attachment getAttachment(string fileName)
    //{
    //    //if (File.Exists(fileName))
    //    //    return new System.Net.Mail.Attachment(fileName);
    //    //else
    //        return null;
    //}

    /// <summary>
    /// This will get the default Email ID from Configuration Table in Company database
    /// </summary>
    /// <returns></returns>
    private string GetDefaultMailID()
    {
        HDDatabase HDD = new HDDatabase();
        string result = "";
        try
        {
            string sql = "select mem_value2 from sy_acr_mem where af_row_id = 'b13034b44961ff77'";
            result = HDD.GetColumnValue(sql);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("FeedBack.aspx : GetDefaultMailID " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }
    private void setPageTitle()
    {
        try
        {
            if (Session["pageTitle"] != null)
            {
                Page.Header.Title = Session["pageTitle"].ToString();
            }
            else
            {
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini"))
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini");
                    Session["pageTitle"] = sr.ReadLine();
                    Page.Header.Title = Session["pageTitle"].ToString();
                    sr.Close();
                    sr = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setPageTitle function. Error: " + e.Message);
        }
    }
}
